using Blog2025.Application.Common;
using Blog2025.Application.Dto;
using Blog2025.Domain.Entities.App;
using Blog2025.Domain.Filters;
using Blog2025.Domain.Repositories;

namespace Blog2025.Application.Services;

public class PermissionAppServices : IPermissionAppServices
{
    private readonly IRepository<AppPermission> _PerRep;
    private readonly IFilter<AppPermission> _filter;
    public PermissionAppServices(IRepository<AppPermission> PerRep ,IFilter<AppPermission> filter)
    {
        _PerRep=PerRep;
        _filter=filter;
    }
    public async Task CreatePermissionAsync(CreatePermissionDto dto)
    {
        var per=new AppPermission{Name=dto.Name};
        await _PerRep.CreateAsync(per);
    }

    public async Task DeletePermissionAsync(Guid id)
    {
        var per=await _PerRep.GetByIdAsync(id)??throw new Exception("权限不存在");
        await _PerRep.DeleteAsync(per);
    }

    public async Task<dynamic> GetAllAsync(PageRequestDto pageRequestDto)
    {
        var per = await _PerRep.GetPagedAsync(pageRequestDto.PageIndex,pageRequestDto.PageSize);
        int totalCount=per.Count();
        int totalPage=(int)Math.Ceiling((double)per.Count() / pageRequestDto.PageSize);
        int pageIndex=pageRequestDto.PageIndex;
        int pageSize=pageRequestDto.PageSize;
        var items=per.Select(p=>new PermissionDto{Id=p.Id,Name=p.Name,Code=p.Code});
        return PageResult.Success(totalCount,totalPage,pageIndex,pageSize,items);
    }
    // 过滤器
    public async Task<dynamic> GetFilterAsync(Dictionary<string ,object> filters)
    {
        var pers=await _PerRep.GetAllAsync();
        return _filter.Filter(pers,filters);
    }

    public async Task<PermissionDto> GetByIdPermission(Guid id)
    {
        var per=await _PerRep.GetByIdAsync(id)?? throw new Exception("权限不存在");
        return new PermissionDto{Id = per.Id, Name = per.Name};
    }

    public async Task UpdatePermissionAsync(Guid id, UpdatePermissionDto dto)
    {
        var per=await _PerRep.GetByIdAsync(id)?? throw new Exception("权限不存在");
        per.Name=dto.Name;
        per.Code=dto.Code;
        await _PerRep.UpdateAsync(per);
    }
}